// pages/coupon/couponHistory/couponHistory.js
const couponService = require('../../../api/couponService.js')

//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 'DISCOUNT',
    couponList: [],
    allCouponsList: [],
    page: 1,
    externalPage: 0,
    pageSize: 10,
    limit: 10,
    member: {},
    noCouponData: false
  },
  // 前往券详情页面
  toCouponDetails: function (val) {
    console.log(val.currentTarget.dataset.activityid, val.currentTarget.dataset.type)
    const isExternal = val.currentTarget.dataset.external
    const couponActivityId = val.currentTarget.dataset.activityid
    const type = val.currentTarget.dataset.type
    const couponsList = this.data.allCouponsList
    const id = val.currentTarget.dataset.id
    if (!isExternal) {
      wx.navigateTo({
        url: '../couponDetails/couponDetails?couponActivityId=' + couponActivityId + '&type=' + type + '&couponId=' + id + '&isExternal=' + isExternal
      })
    } else {
      // 外部券详情跳转
      let tempCoupons = null
      couponsList.forEach(item => {
        if (item.externalCardNum === id) {
          tempCoupons = item
        }
      })

      let coupon = JSON.stringify(tempCoupons)
      console.log(coupon)
      wx.navigateTo({
        url: '../couponDetails/couponDetails?couponActivityId=' + couponActivityId + '&type=' + type + '&couponId=' + id + '&isExternal=' + isExternal + '&coupon=' + coupon
      })
    }
  },
  queryHistoryCoupons: function (page, pageSize, memberMobile, functionEquals) {
    const that = this
    let postData = {
      page: page,
      pageSize: pageSize,
      memberMobileEquals: memberMobile,
      statusEquals: 'HISTORY',
      searchCount: true,
      orderDirection: 'desc',
      orderField: 'assign_time'
    }
    if (functionEquals === 'FREESHIP') {
      postData = {
        ...postData,
        functionEquals: functionEquals
      }
    } else {
      postData = {
        ...postData,
        functionEquals: ['CASH', 'DISCOUNT', 'GIFT'],
      }
    }
    console.log(postData.functionEquals)
    let couponList = []
    let tempList = couponService.query(postData).then(res => {
      if (res.records && res.records.length > 0) {
        that.data.couponsList = [];
        res.records.forEach(item => {
          var tempItem = {
            id: item.id,
            faceValue: item.faceValue,
            balance: item.balance,
            couponTypeName: item.couponTypeName,
            couponActivityName: item.couponActivityName,
            bytimeStart: item.bytimeStart,
            bytimeEnd: item.bytimeEnd,
            status: item.status,
            statusDesc: that.handleCouponStatus(item.status),
            rate: item.rate || item.rate === 0 ? (item.rate * 10).toFixed(1) : '',
            function: item.function,
            name: that.handleCouponName(item.function),
            couponActivityId: item.couponActivityId,
            isExternal: false
          }
          if (item.bytimeStart) {
            // let startTime = item.bytimeStart.split(' ')[0]
            // let endTime = item.bytimeEnd.split(' ')[0]
            let startTime = item.bytimeStart.slice(0, 16)
            let endTime = item.bytimeEnd.slice(0, 16)
            let effectiveTime = startTime + ' ~ ' + endTime
            tempItem = {
              ...tempItem,
              effectiveTime: effectiveTime
            }
          } else {
            tempItem = {
              ...tempItem,
              effectiveTime: ''
            }
          }
          if (functionEquals === 'DISCOUNT') {
            if (item.function !== 'FREESHIP') {
              couponList.push(tempItem)
            }
          } else {
            couponList.push(tempItem)
          }
        })
        let tempCouponsList = []
        tempCouponsList = [].concat(that.data.allCouponsList)
        tempCouponsList = tempCouponsList.concat(res.records)
        that.setData({
          allCouponsList: tempCouponsList
        })
      }
      return couponList
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
      return []
    })
    return tempList
  },
  handleCouponName: function (name) {
    if (name === 'FREESHIP') {
      return '运费券'
    } else if (name === 'DISCOUNT') {
      return '折扣券'
    } else if (name === 'CASH') {
      return '现金券'
    } else if (name === 'GIFT') {
      return '礼品券'
    } else {
      return '优惠券'
    }
  },
  handleCouponStatus: function (status) {
    if (status === 'OPEN') {
      return '已发放'
    } else if (status === 'USED') {
      return '已使用'
    } else if (status === 'EXPIRE') {
      return '已过期'
    } else if (status === 'CANCEL') {
      return '已作废'
    } else if (status === 'MADE') {
      return '已生成'
    } else {
      return '已领取'
    }
  },
  // 渲染查询到的券数据
  setCoupons: function (coupons) {
    const that = this
    let tempCoupons = that.data.couponList
    tempCoupons = tempCoupons.concat(coupons)
    console.log(tempCoupons)
    that.setData({
      couponList: tempCoupons, // 优惠券
      load: false
    })
  },
  // 查询外部券未使用
  queryExternalCoupons: function () {
    const that = this
    let tempList = []
    let couponList = []
    let tempPage = that.data.externalPage
    let memberId = that.data.member.id
    let pageSize = that.data.pageSize
    let postData = {
      memberId: memberId,
      page: tempPage,
      pageSize: pageSize,
      state:'HISTORY'
    }
    let listData = couponService.queryExternalCoupons(postData).then(res => {
      wx.hideToast()
      console.log(res)
      if (res && res.length > 0) {
        let tempExternalList = []
        res.forEach(item => {
          tempExternalList.push(item)
          var tempItem = {
            id: item.externalCardNum,
            faceValue: item.faceValue,
            balance: item.balance,
            couponTypeName: item.couponTypeName,
            couponActivityName: item.couponActivityName,
            bytimeStart: item.bytimeStart,
            bytimeEnd: item.bytimeEnd,
            status: item.status,
            statusDesc: that.handleCouponStatus(item.status),
            rate: item.rate || item.rate === 0 ? (item.rate * 10).toFixed(1) : '',
            function: item.function,
            name: that.handleCouponName(item.function),
            couponActivityId: item.couponActivityId,
            isExternal: true
          }
          if (item.bytimeStart) {
            let startTime = item.bytimeStart.split(' ')[0]
            let endTime = item.bytimeEnd.split(' ')[0]
            let effectiveTime = startTime + ' 至 ' + endTime
            tempItem = {
              ...tempItem,
              effectiveTime: effectiveTime
            }
          } else {
            tempItem = {
              ...tempItem,
              effectiveTime: ''
            }
          }
          if (that.data.type === 'DISCOUNT') {
            if (item.function !== 'FREESHIP') {
              couponList.push(tempItem)
            }
          } else {
            // couponList.push(tempItem)
          }
        })
        let tempCouponsList = []
        tempCouponsList = [].concat(that.data.allCouponsList)
        tempCouponsList = tempCouponsList.concat(tempExternalList)
        that.setData({
          allCouponsList: tempCouponsList
        })
      }
      return couponList
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
      return []
    })
    Promise.all([listData]).then(res => {
      console.log(res)
      if (res[0] && res[0].length > 0) {
        console.log(res[0])
        that.setCoupons(res[0])
        tempPage++
        that.setData({
          externalPage: tempPage
        })
      } else {
        that.setData({
          load: false,
          noCouponData: true
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    console.log(options)
    if (options.type) {
      that.setData({
        type: options.type
      })
    }
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        let memberMobile = app.globalData.userInfo.member.mobile
        that.setData({
          member: app.globalData.userInfo.member
        })
        let functionEquals = that.options.type
        let coupons = that.queryHistoryCoupons(1, 10, memberMobile, functionEquals)
        Promise.all([coupons]).then(res => {
          console.log(res[0])
          if (res[0] && res[0].length > 0) {
            that.setData({
              couponList: res[0]
            })
            if (res[0].length < that.data.limit) {
              // 查询到的内部券数量不够一屏，查询外部券
              console.log('内部券数量不够，查询外部券')
              that.queryExternalCoupons()
            }
          } else {
            that.setData({
              couponList: []
            })
            that.queryExternalCoupons()
          }
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("onPullDownRefresh")
    const that = this
    that.setData({
      page: 1,
      externalPage: 0
    })
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        let memberMobile = app.globalData.userInfo.member.mobile
        let functionEquals = that.data.type
        let coupons = that.queryHistoryCoupons(1, 10, memberMobile, functionEquals)
        Promise.all([coupons]).then(res => {
          console.log(res[0])
          if (res[0] && res[0].length > 0) {
            that.setData({
              couponList: res[0]
            })
            if (res[0].length < that.data.limit) {
              // 查询到的内部券数量不够一屏，查询外部券
              console.log('内部券数量不够，查询外部券')
              that.queryExternalCoupons()
            }
          } else {
            that.setData({
              couponList: []
            })
            that.queryExternalCoupons()
          }
          wx.stopPullDownRefresh()
        })
      }
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom")
    this.loadingCoupon()
  },
  loadingCoupon: function () {
    const that = this
    that.setData({
      load: true
    })
    let index = that.data.page
    index++
    let functionEquals = that.data.type
    let tempList = that.queryHistoryCoupons(index, that.data.pageSize, that.data.member.mobile, functionEquals)
    Promise.all([tempList]).then(res => {
      if (res[0] && res[0].length > 0) {
        console.log(res[0])
        that.setCoupons(res[0])
        that.setData({
          page: index
        })
        if (res[0].length < that.data.limit) {
          // 查询到的内部券数量不够一屏，查询外部券
          console.log('内部券数量不够，查询外部券')
          that.queryExternalCoupons()
        }
      } else {
        // 内部券加载完开始查询外部券
        console.log('123')
        that.queryExternalCoupons()
      }
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})